import cn.fcj.f20240328.fsocket.ReadDataEntity;
import cn.fcj.f20240328.fsocket.base.FBaseNIOSocket;
import cn.fcj.f20240328.fsocket.base.ISocketEventHandler;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

/**
 * @项目名称:FSocket
 * @功能描述:处理读消息粘包分包问题//包协议：包=包头(4byte)+包体，包头内容为包体的数据长度
 * @开发　者:mochhk
 * @邮　　箱:mochhk@163.com
 * @CreateDate:2024/3/30 16:58
 */
public class SocketFixedLengthHandlerImp implements ISocketEventHandler {

    @Override
    public ByteBuffer sendData(SelectionKey key, byte[] msg) throws IOException {
        ByteBuffer byteBuffer = ByteBuffer.allocate(msg.length);
        byteBuffer.put(msg);
        return byteBuffer;
    }

    @Override
    public void receiveDataForChannel(SelectionKey key) throws IOException {
        SocketChannel channel = (SocketChannel) key.channel();
        System.out.println("channelReadable===ChannelLengthHandlerImp====================开始=====");
        readForAllocationData(channel);
//        readData(channel);
    }

    @Override
    public void exceptionHandler(Exception e, FBaseNIOSocket.ErrorCode errorCode, SelectionKey key) {

    }

    @Override
    public void onConnected(SelectionKey key) throws IOException {

    }

    /**
     * 以消息内容的长度设置缓冲区的大小，一次读取一个完整的消息
     * @param channel
     * @throws IOException
     */
    public void readForAllocationData(SocketChannel channel) throws IOException{
        ByteBuffer bodyBuffer=ByteBuffer.allocate(ReadDataEntity.BUFFER_LENGTH);
        int len=-1;
        ReadDataEntity readDataEntity=new ReadDataEntity();
        len=ReadDataEntity.readBuffer(channel,bodyBuffer);
        if(len==ReadDataEntity.BUFFER_LENGTH){
            bodyBuffer.flip();
            System.out.println("channelReadable=="+channel.getRemoteAddress().toString()+"===finished===:" + readDataEntity.bodyToString());
            bodyBuffer.clear();
        }
    }
}
